package com.lam.communication;


import java.security.PublicKey;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.lam.fundamental.R;

public class SMSActivity extends Activity {

	private Button bt_send;
	private EditText et_phone;
	private EditText et_content;
	private static final String SMS_SEND_ACTION="SMS_SEND_ACTION";
	private static final String SMS_DELIVERED_ACTION="SMS_DELIVERED_ACTION";
	private SMSReciver mReciver1;
	private SMSReciver mReciver2;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sms);
		bt_send=(Button)findViewById(R.id.bt_smsSend);
		et_phone=(EditText)findViewById(R.id.et_smsPhone);
		et_content=(EditText)findViewById(R.id.et_smsContent);
		
		
		
		bt_send.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String phone=et_phone.getText().toString().trim();
				String content=et_content.getText().toString().trim();
				Intent itSend=new Intent(SMS_SEND_ACTION);
				Intent itDelivered=new Intent(SMS_DELIVERED_ACTION);
				
				if(phone.equals("")||content.equals("")){
					Toast.makeText(SMSActivity.this, "Phone number or content can't  be empty!", Toast.LENGTH_LONG).show();
				}
				SmsManager smsManager = SmsManager.getDefault();
				
				try {
					PendingIntent sendPI = PendingIntent.getBroadcast(SMSActivity.this, 
							0,itSend, 0);
					PendingIntent deliveredPI=PendingIntent.getBroadcast(SMSActivity.this, 0, itDelivered, 0);
					
					smsManager.sendTextMessage(phone, null, content, sendPI,deliveredPI);
					Toast.makeText(SMSActivity.this, "Message sent!", Toast.LENGTH_LONG).show();
				} catch (Exception e) {
					// TODO: handle exception
					Toast.makeText(SMSActivity.this, "Message sent faild!", Toast.LENGTH_LONG).show();
					e.printStackTrace();
				}
			}
		});
		
		
		
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		IntentFilter mFilter1=new IntentFilter(SMS_SEND_ACTION);
		mReciver1=new SMSReciver();
		registerReceiver(mReciver1, mFilter1);
		
		mFilter1=new IntentFilter(SMS_DELIVERED_ACTION);
		mReciver2=new SMSReciver();
		registerReceiver(mReciver2, mFilter1);
		
		super.onResume();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		unregisterReceiver(mReciver1);
		unregisterReceiver(mReciver2);
		super.onPause();
	}
	
	
}
